//
//  MatchCenterCtrl.m
//  cutter
//
//  Created by mac on 16/1/12.
//  Copyright © 2016年 e360. All rights reserved.
//
#import "UserCenterPick.h"
#import "ProductCenterCtrl.h"
#import "MatchCenterCtrl.h"
#import "MatchDetailCtrl.h"
#import "MatchEdit.h"


#pragma mark -
#pragma mark MatchCenterCell
@interface MatchCenterCellTags : UIButton
@end
@implementation MatchCenterCellTags
-(void)setSelected:(BOOL)selected{
    [super setSelected:selected];
    if (selected) {
        [self setBackgroundColor:[UIColor colorWithHex:0x4794EF]];
    }else{
        [self setBackgroundColor:[UIColor colorWithHex:0xBBBBBB]];
    }
}
@end
//
@implementation MatchCenterCell
- (void)awakeFromNib{
    [super awakeFromNib];
    if (self.infoView && self.type == 0) {
        [self.infoView setHidden:YES];
    }
    if (self.tipsView) {
        [self.tipsView setHidden:YES];
    }
    if (self.selectView) {
        [self.selectView setHidden:YES];
    }
}
- (void)setSelected:(BOOL)selected{
    [super setSelected:selected];
    [self.selectView setSelected:selected];
}
@end


#pragma mark -
#pragma mark MatchCenterList
@implementation MatchCenterList
-(void)viewDidLoad{
    [super viewDidLoad];
    //
    [self.deleteView setHidden:YES];
    [self.deleteView addTarget:self action:@selector(deleteTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.editView addTarget:self action:@selector(editTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectionView setAllowsMultipleSelection:YES];
    //
    [self.collectionView.headerView addTarget:self action:@selector(headerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.collectionView.headerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.collectionView.headerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.collectionView.headerView setTitle:@"下拉刷新" forState:TMRefreshStateNormal];
    //
    [self.collectionView.footerView addTarget:self action:@selector(footerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.collectionView.footerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.collectionView.footerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.collectionView.footerView setTitle:@"上拉翻页" forState:TMRefreshStateNormal];
    //
    [self.searchView setDelegate:self];
    [self headerRefresh:nil];
}
//
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.condition setValue:textField.text forKey:@"keyword"];
    [self headerRefresh:nil];
    return YES;
}
- (void)headerRefresh:(TMRefresh*)sender{
    if (sender == nil) {
        sender = self.collectionView.headerView;
        [sender beginRefreshing];
    }
    //
    __weak MatchCenterList *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [this.condition setValue:@(1) forKey:@"page"];
        [this setData:[AppData userMatch:this.condition]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender endRefreshing];
            [this.collectionView reloadData];
        });
    });
}
- (void)footerRefresh:(TMRefresh*)sender{
    __weak MatchCenterList *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSInteger p = [[self.condition objectForKey:@"page"] intValue] + 1;
        [this.condition setValue:@(p) forKey:@"page"];
        //
        NSArray *app = [AppData userMatch:this.condition];
        [this.data addObjectsFromArray:app];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender setFinish:[app count]==0];
            [sender endRefreshing];
            //
            [this.collectionView reloadData];
        });
    });
}
- (NSMutableDictionary *)condition{
    if (_condition == nil) {
        [self setCondition:[NSMutableDictionary dictionary]];
    }
    [_condition setValue:[NSNumber numberWithBool:NO] forKey:@"isshare"];
    [_condition setValue:@(50) forKey:@"limit"];
    return _condition;
}
//
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.data count] + 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == 0) {
        MatchCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"addIdentifier" forIndexPath:indexPath];
        return cell;
    }
    NSDictionary *item = [self.data objectAtIndex:indexPath.item - 1];
    MatchCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    [cell.titieView setText:[AppData objToString:[item objectForKey:@"matchname"] lable:nil]];
    [cell.priceView setText:[AppData priceToString:[item objectForKey:@"price"] lable:nil]];
    [AppData loadImage:[item objectForKey:@"pic"] view:cell.imageView];
    [cell.selectView setHidden:self.deleteView.hidden];
    //
    if ([[item objectForKey:@"isshare"] boolValue]) {
        if ([[item objectForKey:@"verify"] boolValue]) {
            [cell.tipsView setSelected:YES];
        }else{
            [cell.tipsView setSelected:NO];
        }
        [cell.tipsView setHidden:NO];
    }else{
        [cell.tipsView setHidden:YES];
    }
    //
    return cell;
}
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    return self.deleteView.hidden;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
    if (indexPath) {
        __weak MatchCenterList *this = self;
        if (indexPath.item > 0) {
            if ([segue.destinationViewController isKindOfClass:MatchDetailCtrl.class]) {
                MatchDetailCtrl *ctrl = segue.destinationViewController;
                [ctrl setData:[self.data objectAtIndex:indexPath.item - 1]];
                [ctrl setOnSelected:^(id target, id result){
                    [this headerRefresh:nil];
                    [this dismissViewControllerAnimated:YES completion:nil];
                }];
            }
        }else{
            if ([segue.destinationViewController isKindOfClass:MatchEdit.class]) {
                MatchEdit *ctrl = segue.destinationViewController;
                [ctrl setOnSelected:^(id target, id result){
                    [this headerRefresh:nil];
                    [this dismissViewControllerAnimated:YES completion:nil];
                }];
            }
        }
    }
}
//
- (void)editTouch:(UIButton*)sender{
    [sender setSelected:!sender.selected];
    [self.deleteView setHidden:!sender.selected];
    //
    NSArray *cells = [self.collectionView visibleCells];
    for (MatchCenterCell *cell in cells) {
        if ([cell isKindOfClass:MatchCenterCell.class]) {
            [cell.selectView setHidden:!sender.selected];
        }
    }
}
- (void)deleteTouch:(UIButton*)sender{
    __weak typeof(self) this = self;
    [UIAlertController showAt:self title:nil message:@"删除选中的搭配？" buttons:@[@"删除",@"取消"] handler:^(UIAlertAction *action) {
        if ([action.title isEqualToString:@"删除"]) {
            NSArray *indexPaths = [this.collectionView indexPathsForSelectedItems];
            if ([indexPaths count] > 0) {
                NSArray *temp = [indexPaths sortedArrayUsingComparator:^NSComparisonResult(NSIndexPath *obj1, NSIndexPath *obj2) {
                    if (obj1.item > obj2.item) {
                        return -1;
                    }
                    if (obj1.item < obj2.item) {
                        return 1;
                    }
                    return 0;
                }];
                //
                NSMutableArray *dels = [NSMutableArray array];
                for (NSIndexPath *indexPath in temp) {
                    id item = [this.data objectAtIndex:indexPath.item-1];
                    [this.data removeObject:item];
                    [dels addObject:item];
                }
                [AppData userDeleteMatch:dels];
                [this.collectionView deleteItemsAtIndexPaths:indexPaths];
            }
            [this editTouch:this.editView];
        }
    }];
}
@end


#pragma mark -
#pragma mark MatchCenterCtrl
@implementation MatchCenterCtrl
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setIsshare:YES];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTipsView:[[MatchClassifyTips alloc] initWithFrame:CGRectZero]];
    //
    [self.collectionView.headerView addTarget:self action:@selector(headerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.collectionView.headerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.collectionView.headerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.collectionView.headerView setTitle:@"下拉刷新" forState:TMRefreshStateNormal];
    //
    [self.collectionView.footerView addTarget:self action:@selector(footerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.collectionView.footerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.collectionView.footerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.collectionView.footerView setTitle:@"上拉翻页" forState:TMRefreshStateNormal];
    //
    [self.collectView addTarget:self action:@selector(collectTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.screenView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    //
    [self.mixedView addTarget:self action:@selector(sortTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.salesView addTarget:self action:@selector(sortTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.priceView addTarget:self action:@selector(sortTouch:) forControlEvents:UIControlEventTouchUpInside];
    //
    [self hiddenLeft:NO];
    [self setType:self.type];
    //
    [self.menuView.textField setDelegate:self];
    [self.menuView setCurrentTitle:@"搭配"];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.condition setValue:textField.text forKey:@"keyword"];
    [self headerRefresh:nil];
    return YES;
}
-(void)setType:(NSInteger)type{
    _type = type;
    if (type == 0) {
        [self.collectView setHidden:YES];
    }else{
        [self.collectView setHidden:NO];
    }
    [self headerRefresh:nil];
}
//
-(void)setIsshare:(BOOL)isshare{
    _isshare = isshare;
    //
    if (isshare) {
        [self.condition setValue:@(1) forKey:@"isshare"];
        [self.condition setValue:@(1) forKey:@"verify"];
    }else{
        [self.condition setValue:@(0) forKey:@"isshare"];
    }
}
- (void)headerRefresh:(TMRefresh*)sender{
    if (sender == nil) {
        sender = self.collectionView.headerView;
        [sender beginRefreshing];
    }
    //
    __weak MatchCenterCtrl *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [this.condition setValue:@(1) forKey:@"page"];
        [this setData:[AppData userMatch:this.condition]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender endRefreshing];
            [self.nullView setHidden:[this.data count]>0];
            [this.collectionView.footerView setFinish:NO];
            //
            [this.collectionView reloadData];
        });
    });
}
- (void)footerRefresh:(TMRefresh*)sender{
    __weak MatchCenterCtrl *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSInteger p = [[self.condition objectForKey:@"page"] intValue] + 1;
        [this.condition setValue:@(p) forKey:@"page"];
        //
        NSArray *app = [AppData userMatch:this.condition];
        [this.data addObjectsFromArray:app];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender setFinish:[app count]==0];
            [sender endRefreshing];
            //
            [this.collectionView reloadData];
        });
    });
}
- (NSMutableDictionary *)condition{
    if (_condition == nil) {
        [self setCondition:[NSMutableDictionary dictionary]];
    }
    [_condition setValue:@(50) forKey:@"limit"];
    return _condition;
}
//
- (void)hiddenLeft:(BOOL)animation{
    [self.leftLayout setConstant:-250];
    [self.view setNeedsUpdateConstraints];
    if (animation) {
        [UIView beginAnimations:nil context:nil];
        [self.view layoutIfNeeded];
        [UIView commitAnimations];
    }
}
- (void)showLeft:(BOOL)animation{
    [self.leftLayout setConstant:0];
    [self.view setNeedsUpdateConstraints];
    if (animation) {
        [UIView beginAnimations:nil context:nil];
        [self.view layoutIfNeeded];
        [UIView commitAnimations];
    }
}
- (IBAction)exitTouch:(UIButton*)sender {
    if (sender.selected) {
        if (self.navigationController) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }else{
        IndexHomeCtrl *tabbar = (id)self.splitViewController;
        if ([tabbar isKindOfClass:IndexHomeCtrl.class]) {
            [tabbar showMenu];
        }
    }
}
- (void)ctrlTouch:(UIButton*)sender{
    if (sender.selected) {
        [sender setSelected:NO];
        [self hiddenLeft:YES];
    }else{
        [sender setSelected:YES];
        [self showLeft:YES];
    }
}
- (void)collectTouch:(UIButton*)sender{
}
- (void)sortTouch:(UIButton*)sender{
    if (sender==self.priceView) {
        [self.mixedView setSelected:NO];
        [self.salesView setSelected:NO];
        
        if (self.priceView.selected == YES) {
            [self.priceView setSort:!self.priceView.sort];
        }else{
            [self.priceView setSelected:YES];
            [self.priceView setSort:NO];
        }
        if (self.priceView.sort) {
            [self.condition setValue:@"price|desc" forKey:@"sort"];
        }else{
            [self.condition setValue:@"price|asc" forKey:@"sort"];
        }
    }else{
        [self.priceView setSelected:NO];
        [self.mixedView setSelected:NO];
        [self.salesView setSelected:NO];
        [sender setSelected:YES];
        //
        [self.condition setValue:@"" forKey:@"spacearea"];
        if (sender == self.salesView) {
            [self.condition setValue:@"postdate|desc" forKey:@"sort"];
        }else{
            [self.condition setValue:@"id|asc" forKey:@"sort"];
        }
    }
    [self headerRefresh:nil];
}
//
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.data count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MatchCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    if(indexPath.item < [self.data count]){
        id item = [self.data objectAtIndex:indexPath.item];
        [cell.priceView setText:[AppData priceToString:[item objectForKey:@"price"] lable:nil]];
        [cell.titieView setText:[AppData objToString:[item objectForKey:@"matchname"] lable:nil]];
        [AppData loadImage:[item objectForKey:@"pic"] view:cell.imageView];
        [cell setType:self.type];
    }
    return cell;
}
//
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [scrollView setNeedsLayout];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [scrollView setNeedsLayout];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender{
    __weak MatchCenterCtrl *this = self;
    //
    //顶部导航
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *ctrl = segue.destinationViewController;
        if ([[ctrl.viewControllers firstObject] isKindOfClass:UserCenterSelect.class]) {
            UserCenterSelect *root = [ctrl.viewControllers firstObject];
            [root setOnSelected:^(id target, id result){
                [this dismissViewControllerAnimated:YES completion:^{
                    if(result){
                        if([segue.identifier isEqualToString:@"favorite"]){
                            [TMGlobal setValue:@(3) forKey:@"clientTag"];
                            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
                        }
                        if([segue.identifier isEqualToString:@"cart"]){
                            [TMGlobal setValue:@(4) forKey:@"clientTag"];
                            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
                        }
                    }
                }];
            }];
        }
    }
    //
    __weak UINavigationController *root = segue.destinationViewController;
    if ([segue.identifier isEqualToString:@"MatchScreen"]) {
        __weak MatchClassifyCtrl *screen = [root.viewControllers firstObject];
        [screen setData:[AppData userMatchScreen:nil]];
        [screen setOnSelected:^(id sender, id result){
            if (sender==nil && result==nil) {
                NSArray *ids = [NSArray arrayWithObjects:@(379), @(397), @(398), nil];
                NSArray *keys = [NSArray arrayWithObjects:@"styleid", @"spaceid", @"colorid", nil];
                for (id key in keys) {
                    [this.condition setValue:nil forKey:key];
                }
                for (id group in screen.tips.allKeys) {
                    NSDictionary *value = [screen.tips objectForKey:group];
                    for (id item in value.allKeys) {
                        NSInteger i = [ids indexOfObject:[[value objectForKey:item] objectForKey:@"parentid"]];
                        if (i != NSNotFound) {
                            id key = [keys objectAtIndex:i];
                            [this.condition setValue:[value.allKeys componentsJoinedByString:@","] forKey:key];
                        }
                        break;
                    }
                }
                [this headerRefresh:nil];
                [this.tipsView reloadTips];
            }else{
                CGRect rect = [root.view convertRect:root.view.bounds toView:this.view];
                [this.tipsView showFromRect:CGRectOffset(rect, rect.size.width, 0) atView:this.view];
                [this.tipsView setTips:screen.tips];
                [this.tipsView setData:result];
                [this.tipsView reloadTips];
                //
                [this.tipsView setOnSelected:^(id sender, id result){
                    if (result) {
                        [screen setTips:result];
                        [screen reloadTips];
                        screen.onSelected(nil, nil);
                    }
                }];
            }
        }];
    }
    //
    if ([segue.destinationViewController isKindOfClass:MatchDetailCtrl.class]) {
        MatchDetailCtrl *ctrl = segue.destinationViewController;
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
        if (indexPath) {
            [ctrl setData:[self.data objectAtIndex:indexPath.item]];
            [ctrl setOnSelected:self.onSelected];
            [ctrl setSource:self.data];
            [ctrl setType:self.type];
        }
    }
}
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(nullable id)sender{
    if ([TMGlobal valueForKey:@"client"]){
        if ([identifier isEqualToString:@"favorite"]) {
            [TMGlobal setValue:@(3) forKey:@"clientTag"];
            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
            return NO;
        }
        if ([identifier isEqualToString:@"cart"]) {
            [TMGlobal setValue:@(4) forKey:@"clientTag"];
            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
            return NO;
        }
        if ([identifier isEqualToString:@"client"]) {
            [TMGlobal setValue:nil forKey:@"clientTag"];
            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
            return NO;
        }
    }
    return YES;
}
@end